// components/custom-popup.ts
import { commonTagList, getCodeRegion } from '../../utils/api.js'
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    defaultValue: { // 等下删除
      type: String,
      observer(newVal) {
        setTimeout(() => {
          // this.handleData(newVal)
        }, 1000)
      }
    },
    dataList: {
      type: Array,
      observer(newVal) {
        // this.handleData(newVal)
      }
    },
    title: {
      type: String,
      value: '选择器'
    },
    pickerParams: {
      type: Object,
      value: {
        show: false,
        pickerType: 'gender',
        defaultValue: ''
      },
      observer(newVal) {
        if (newVal) {
          // 在这里处理值变化逻辑
          if (newVal.show && newVal.pickerType === 'date') {
            // this.populatePicker();
          }
          // 兴趣
          if (newVal.show && newVal.pickerType == "interest") {
            this.getInterest()
          }
          // 职业技能
          if (newVal.show && newVal.pickerType == "professionId") {
            this.getProfession()
          }
          // 省市区
          if (newVal.show && newVal.pickerType == "areaRegion" || newVal.show && newVal.pickerType == "areaHomeRegion") {
            this.getRegionList()
          }
          // if (newVal.defaultValue) { // 判断如果有默认值
          //   this.handleData(newVal.defaultValue, this.data.dataList)
          // }
          if (newVal.show && (newVal.pickerType != "areaRegion" || newVal.pickerType != "areaHomeRegion")) { // 回显
            if (newVal.defaultValue) { // 判断如果有默认值
              this.handleData(newVal.defaultValue, this.data.dataList)
            }
          }
          // 性别
          // if (newVal.show && newVal.pickerType == "gender") {
          //   // this.handleData(newVal.defaultValue, this.data.dataList)
          //   this.handleData(2, this.data.dataList)
          //   // this.setData({
          //   //   pickerValue: [1]
          //   // })
          // }
          this.setData({
            visible: newVal.show
          })
        }
      }
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    animation: null as any | null, // WechatMiniprogram.Animation
    pickerDatas: {
      gender: { title: '性别', data: ['全部', '男性', '女性', '其他'] },
      MBTI: { title: 'MBTI', data: ['INTP', 'INTJ', 'ENTJ', 'ENTP', 'ENFP', 'INFP', 'ENFJ', 'INFJ', 'ISTJ', 'ISFJ', 'ESTJ', 'ESFJ', 'ISTP', 'ISFP', 'ESTP', 'ESFP'] },
      language: { title: '选择语言', data: ['English', '简体中文', '繁体中文'] },
      date: { title: '选择日期' },
      partnerType: {
        title: '搭子',
        data: ['在线游戏', '虚拟读书俱乐部', '电影之夜', '密室逃脱', '欢乐时光']
      },
      interest: {
        title: '兴趣',
        data: []
      }
    },
    yearColumns: [1900],
    monthColumns: ['01'],
    dayColumns: ['01'],
    pickerValue: [0],
    pickerRegionValue: [0, 0 ,0],
    provincesColumns: [
      {
        citys: [],
        province: '',
        code: ''
      }
    ],
    provincesCodeList: [],
    cityColumns: [
      {
        areas: [],
        city: '',
        code: ''
      }
    ],
    cityCodeList: [],
    regionColumns: [
      {
        area: '',
        code: ''
      }
    ],
    regionCodeList: [],
    currentObj: {},
    allDataList: [],
    parentCode: '',
    currentIndexList: [0, 0, 0]
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getRegionList() {
      const that = this
      // 判断缓存中是否有区域数据，如果没有，就重新请求数据
      const storageAreaRegion = wx.getStorageSync('areaRegion')
      if (!storageAreaRegion || storageAreaRegion.length < 0) {
        const params = {}
        getCodeRegion(params).then((res: any) => {
          wx.setStorageSync('areaRegion', res)
          that.setData({
            provincesColumns: res,
            cityColumns: res[0].citys,
            regionColumns: res[0].citys[0].areas
          }, () => {
            that.handleRegionData()
          })
          // if (type === 1) { // 市
          //   this.setData({
          //     cityColumns: labelList,
          //     cityCodeList: codeList
          //   })
          //   // 再调用此方法，获取区的列表
          //   return this.getRegionList(res[0].code, 2)
          // } else if (type === 2) { // 区
          //   this.setData({
          //     regionColumns: labelList,
          //     regionCodeList: codeList
          //   })
          //   // 区后面不再调了
          //   return false;
          // } else { // 省
          //   this.setData({
          //     provincesColumns: labelList,
          //     provincesCodeList: codeList
          //   })
          //   // 再调用此方法，获取市的列表
          //   return this.getRegionList(res[0].code, 1)
          // }
        })
      } else {
        that.setData({
          provincesColumns: storageAreaRegion,
          cityColumns: storageAreaRegion[0].citys,
          regionColumns: storageAreaRegion[0].citys[0].areas,
        }, () => {
          that.handleRegionData()
        })
      }
    },
    /**
     * 处理区域数据回显
     */
    handleRegionData() {
      const { provincesColumns, pickerParams } = this.data
      const regionNameList = pickerParams.defaultValue
      const that = this
      // defaultValue  正常情况下，三个元素，第一个值是省，第二个是市，第三个是区
      if (regionNameList && regionNameList.length > 1) {
        // 通过js的数组方法findIndex找到下标
        // 通过名称寻找省
        let provincesNameIndex= provincesColumns.findIndex((item: any) => item.province === regionNameList[0]) || 0;
        // 通过code寻找
        let provincesCodeIndex = provincesColumns.findIndex((item: any) => item.code === regionNameList[0]) || 0;
        // let provincesIndex = provincesNameIndex > 0 ? provincesNameIndex : provincesNameIndex
        let provincesIndex = 0
        if (provincesNameIndex != -1 && provincesNameIndex != 0) {
          provincesIndex = provincesNameIndex
        } else {
          provincesIndex = provincesCodeIndex || 0
        }
        
        // 查找市
        let citys: any = provincesColumns[provincesIndex].citys
        let cityNameIndex = citys.findIndex((item: any) => item.city === regionNameList[1]) || 0;
        let cityCodeIndex = citys.findIndex((item: any) => item.code === regionNameList[1]) || 0;
        // let cityIndex = cityNameIndex > 0 ? cityNameIndex : cityCodeIndex
        let cityIndex = 0
        if (cityNameIndex != -1 && cityNameIndex != 0) {
          cityIndex = cityNameIndex
        } else {
          cityIndex = cityCodeIndex || 0
        }
        
        // 查找区
        let areas: any = citys[cityIndex].areas
        let areaNameIndex = areas.findIndex((item: any) => item.area === regionNameList[2]) || 0;
        let areaCodeIndex = areas.findIndex((item: any) => item.code === regionNameList[2]) || 0;
      //  let areaIndex = areaNameIndex || areaCodeIndex
      //  let areaIndex = areaNameIndex > 0 ? areaNameIndex : areaCodeIndex
       let areaIndex = 0
       if (areaNameIndex != -1 && areaNameIndex != 0) {
        areaIndex = areaNameIndex
       } else {
        areaIndex = areaCodeIndex || 0
       }
       const indexList = [provincesIndex,cityIndex, areaIndex]
        that.setData({
          cityColumns: citys,
          regionColumns: areas,
        }, () => {
          that.setData({
            pickerRegionValue: indexList,
          })
        })
      }
    },
    allRegionChange(e: any) {
      const indexList = e.detail.value // 第一个下标是省  第二个下标是市  第三个下标是区
      let { currentIndexList, provincesColumns, cityColumns, pickerRegionValue } = this.data
      const oneFlag = indexList[0] != currentIndexList[0] // 省不一样
      const twoFlag = indexList[1] != currentIndexList[1] // 市不一样
      const threeFlag = indexList[2] != currentIndexList[2] // 区不一样
      // console.log(pickerRegionValue);
      if (oneFlag) { // 如果，第一个的值不一样，那就说明，改变了省，根据省的code去查市
        const obj: any = provincesColumns[indexList[0]]
        // 重置到第一个选项
        // pickerRegionValue = [indexList[0] || 0, 0, 0]
        this.setData({
          cityColumns: obj.citys,
          regionColumns: obj.citys[0].areas,
          // pickerRegionValue
        })
      }
      if (twoFlag) { // 如果，第二个的值不一样，那就说明，改变了市，根据市的code去查区
        const obj: any = cityColumns[indexList[1]]
        // 重置到第一个选项
        // pickerRegionValue = [indexList[0] || 0, indexList[1] || 0, 0]
        this.setData({
          regionColumns: obj.areas,
          // pickerRegionValue
        })
      }
      // if (threeFlag) {
      //   pickerRegionValue = indexList
      // }
      this.setData({
        currentIndexList: indexList,
        // pickerRegionValue
      })
    },
    provincesChange(value: any) {
      console.log(value);
    },
    handleData(value: any, list: any) {
      // const { dataList } = this.data
      let currentIndex = 0;
      list.length > 0 && list.map((item: any, index: any) => {
        if (item.value == value || item.text == value) {
          currentIndex = index
          return
        }
      })
      this.setData({
        pickerValue: [currentIndex || 0]
      })
    },
    /**
     * 获取兴趣列表
     */
    getInterest() {
      const { pickerDatas } = this.data
      const { interest } = pickerDatas
      let params = {
        tagType: 'INTEREST'
      }
      commonTagList(params).then(res => {
        console.log(res);
        interest.data = res
      })
      this.setData({
        pickerDatas
      })
    },
    getProfession() {
      const { pickerDatas } = this.data
      const { interest } = pickerDatas
      let params = {
        tagType: 'INTEREST'
      }
      commonTagList(params).then(res => {
        interest.data = res
      })
      this.setData({
        pickerDatas
      })
    },
    bindChange(event: { detail: { value: number[] } }) {
      const valueArr = event.detail.value;
      const { dataList } = this.data
      let currentObj = valueArr.length > 0 && dataList.length > 0 ? dataList[valueArr[0]] : dataList[0]
      this.setData({
        currentObj,
        pickerValue: valueArr
      })
    },
    dateChange(event: { detail: { value: number[] } }) {
      const valueArr = event.detail.value;
      const year = this.data.yearColumns[valueArr[0]]
      const month = this.data.monthColumns[valueArr[1]]
      this.updateDays(year, Number(month))
      this.setData({ pickerValue: valueArr })
    },
    onCancel() {
      this.triggerEvent('cancel');
      this.setData({ visible: false })
    },
    onConfirm() {
      let { currentObj, dataList, pickerParams, currentIndexList, provincesCodeList, provincesColumns, cityCodeList, cityColumns, regionCodeList, regionColumns } = this.data
      if (pickerParams.pickerType == "areaRegion") { // 省市区选择器
        const provincesIndex = currentIndexList[0]
        const cityIndex = currentIndexList[1]
        const regionIndex = currentIndexList[2]
        const provincesLabel = provincesColumns[provincesIndex].province
        const provincesValue = provincesColumns[provincesIndex].code
        const cityLabel = cityColumns[cityIndex].city
        const cityValue = cityColumns[cityIndex].code
        const regionLabel = regionColumns[regionIndex].area
        const regionValue = regionColumns[regionIndex].code
        const obj = {
          provincesLabel,
          provincesValue,
          cityLabel,
          cityValue,
          regionLabel,
          regionValue
        }
        this.triggerEvent('onConfirm', { value: obj });
        this.setData({ visible: false })
      } else { // 其他选择器
        if (Object.keys(currentObj).length <= 0) {
          if (pickerParams.defaultValue) { // 如果传过来了默认值
            const list = dataList.length > 0 ? dataList.filter(item => item.value == pickerParams.defaultValue) : []
            currentObj = list.length > 0 ? list[0] : {}
          } else { // 否则就默认第一项
            currentObj = dataList.length > 0 ? dataList[0] : {}
          }
        }
        this.triggerEvent('onConfirm', { value: currentObj });
        this.setData({ visible: false })
      }
      this.onCancel()
    },
    populatePicker() {
      const today = new Date();
      // 填充年份
      const yearSelect: number[] = [];
      for (let i = today.getFullYear() - 50; i <= today.getFullYear() + 10; i++) {
        yearSelect.push(i);
      }
      this.setData({ yearColumns: yearSelect })
      // 填充月份
      const monthSelect: string[] = [];
      for (let i = 1; i <= 12; i++) {
        const value = String(i).padStart(2, "0");
        monthSelect.push(value);
      }
      this.setData({ monthColumns: monthSelect })
      const defaultYear = this.data.pickerParams.defaultValue.split('-')[0]
      const defaultMonth = this.data.pickerParams.defaultValue.split('-')[1]
      const defaultDay = this.data.pickerParams.defaultValue.split('-')[2]
      this.updateDays(parseFloat(defaultYear), parseFloat(defaultMonth), parseFloat(defaultDay));
    },
    // 更新日期
    updateDays(year: number, month: number, day?: number) {
      const daysInMonth = new Date(year, month, 0).getDate();
      const daySelect: string[] = [];
      for (let i = 1; i <= daysInMonth; i++) {
        const value = String(i).padStart(2, "0");
        daySelect.push(value);
      }
      this.setData({ dayColumns: daySelect })
      if (day) {
        // 有值则是初始化，赋值历史数据
        const yaerIndex = this.data.yearColumns.indexOf(year)
        const monthIndex = this.data.monthColumns.indexOf(month < 10 ? '0' + month : month.toString())
        const dayIndex = this.data.dayColumns.indexOf(day < 10 ? '0' + day : day.toString())
        this.setData({ pickerValue: [yaerIndex, monthIndex, dayIndex] })
      }
    }
    // closePopup() {
    //   console.log(1122);
    //   this.triggerEvent('cancel', false);
    //   this.setData({ visible: false })
    // },
    // onConfirm (e: any) {
    //   console.log(e);
    // }
  }
})